find all files containing a string in python with glob module

36

import glob
# path of the current directory
path = './'
text_files = glob.glob(path + '**/*.txt',recursive=True)
print(text_files)


for text_file in text_files:
    required_str= 'Python'
    try:
        with open(text_file) as f:
            # read the file as a string
            text_data = f.read()
            # if the string is find
            if(required_str in text_data):
                print(text_file)
    except:
        pass

Comments

Submit
0 Comments